'use client'
import { useState, useEffect, useRef, useCallback } from 'react'
import Image from 'next/image'
import axios from '@/utils/https'
import {
  SidebarButton,
  EditButton,
} from '@/components/CommonButton/CommonButton'
import store from '@/store/index'
import FooterInput from './components/footerInput'
import Markdown from '@/components/Markdown/index'

export default function ChatPage() {
  const [recordStatus, setRecordStatus] = useState(true)
  const [modelStatus, setModelStatus] = useState(false)
  const { list, setMsgList, module } = store.Chat() // Using Zustand store
  const chatContainerRef = useRef<HTMLDivElement>(null)
  const lastMessageRef = useRef<HTMLDivElement | null>(null)
  const resizeObserverRef = useRef<ResizeObserver | null>(null)
  const [autoScroll, setAutoScroll] = useState(true)
  const [isLoading, setIsLoading] = useState(false)
  const [isSend, setIsSend] = useState(false)
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const isFetchingMore = useRef(false)

  // Fetch chat history
  const fetchChat = useCallback(
    async (pageNum: number, prepend = false) => {
      if (isFetchingMore.current) return
      isFetchingMore.current = true
      setIsLoading(true)
      try {
        const res = await axios.get('/apis/chat/msg', {
          params: { page: pageNum, pageSize: 10 },
        })

        const { data, meta } = res
        if (prepend) {
          // Prepend new messages
          setMsgList([...data, ...list])
        } else {
          // Set the fetched messages
          setMsgList(data)
        }
        setHasMore(pageNum < meta.totalPages)
      } catch (err) {
        console.error('Failed to fetch chat messages:', err)
      } finally {
        setIsLoading(false)
        isFetchingMore.current = false
      }
    },
    [setMsgList]
  )

  // Initialize the first page fetch
  useEffect(() => {
    fetchChat(1)
    setPage(1)
  }, [fetchChat])

  // Scroll event handler
  const handleScroll = useCallback(() => {
    const container = chatContainerRef.current
    if (!container) return
    const { scrollTop, scrollHeight, clientHeight } = container

    // Auto-scroll logic
    setAutoScroll(scrollHeight - scrollTop <= clientHeight + 50)

    // Trigger loading more messages on scroll up
    if (scrollTop <= 100 && hasMore && !isFetchingMore.current) {
      const newPage = page + 1
      fetchChat(newPage, true)
      setPage(newPage)
      setIsLoading(true) // Show loading animation when fetching more messages
    }
  }, [page, fetchChat, hasMore])

  // Listen to last message height change to auto-scroll
  useEffect(() => {
    const container = chatContainerRef.current
    if (!container) return
    const lastMessage = container.lastElementChild as HTMLDivElement | null
    if (!lastMessage) return

    if (resizeObserverRef.current) {
      resizeObserverRef.current.disconnect()
    }

    resizeObserverRef.current = new ResizeObserver(() => {
      if (autoScroll) {
        container.scrollTop = container.scrollHeight
      }
    })

    resizeObserverRef.current.observe(lastMessage)

    return () => resizeObserverRef.current?.disconnect()
  }, [list?.length, autoScroll])

  return (
    <div className="w-full h-full flex">
      <div
        className="w-[50vw] h-[80vh] border mt-[5vh] rounded-lg mr-auto ml-auto"
        onClick={() => setModelStatus(false)}
      >
        <div className="h-full flex">
          <div className="flex-1 h-full flex flex-col relative">
            {/* Top button bar */}
            <div className="h-14 flex items-center pl-2">
              {!recordStatus && [
                <SidebarButton
                  key="sidebar"
                  type={2}
                  handleClick={() => setRecordStatus(!recordStatus)}
                />,
                <EditButton key="edit" type={2} handleClick={() => {}} />,
              ]}
              <div
                onClick={(e) => {
                  e.stopPropagation()
                  setModelStatus(!modelStatus)
                }}
                className="h-10 flex cursor-pointer p-2 rounded-md hover:bg-[#f9f9f9] ml-2 font-semibold text-[#7d7d7d]"
              >
                {module}
              </div>
            </div>

            {/* Chat list */}
            <div
              ref={chatContainerRef}
              onScroll={handleScroll}
              className="flex-1 w-full bg-white overflow-y-auto box-border custom-scrollbar"
            >
              {isLoading && list.length === 0 ? (
                <div className="flex justify-center items-center h-full">
                  <p>Loading messages...</p>
                </div>
              ) : list.length === 0 ? (
                <div className="flex justify-center items-center h-full">
                  <p>No messages yet. Start a conversation!</p>
                </div>
              ) : (
                <>
                  {isLoading && (
                    <div className="flex justify-center items-center py-2">
                      <div className="w-8 h-8 border-4 border-t-4 border-gray-300 rounded-full animate-spin"></div>
                    </div>
                  )}
                  {list.map((item, index) => (
                    <div
                      key={index}
                      className={`flex items-center p-3 ${
                        item.sender_type === 'user' ? 'flex-row-reverse' : ''
                      }`}
                      ref={index === list.length - 1 ? lastMessageRef : null}
                    >
                      <div
                        className={`p-3 rounded-lg max-w-[75%] break-words ${
                          item.sender_type === 'user'
                            ? 'bg-primary text-white rounded-br-none'
                            : 'bg-gray-200 text-black rounded-bl-none'
                        }`}
                      >
                        <Markdown content={item.message} />
                      </div>
                    </div>
                  ))}
                  {isSend && (
                    <div className="flex flex-row gap-2 ml-3 mt-5">
                      <div className="w-3 h-3 rounded-full bg-gray-300 animate-bounce [animation-delay:.7s]"></div>
                      <div className="w-3 h-3 rounded-full bg-gray-300 animate-bounce [animation-delay:.3s]"></div>
                      <div className="w-3 h-3 rounded-full bg-gray-300 animate-bounce [animation-delay:.7s]"></div>
                    </div>
                  )}
                </>
              )}
            </div>

            {/* Footer Input */}
            <FooterInput setAutoScroll={setAutoScroll} setIsSend={setIsSend} />
          </div>
        </div>
      </div>
    </div>
  )
}
